<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="800px" :append-to-body="true">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建索引" : "查看索引" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="110px">
      <el-form-item label="Key" prop="key" :rules="[
        { required: true, message: 'Key不能为空', trigger: 'change' },
        {
          pattern: COMMON_CODE_64I_REG.pattern,
          message: '请输入有效的Key',
          trigger: 'change',
        },
      ]">
        <template slot="label">Key
          <el-tooltip popper-class="custom-popper" :content="COMMON_CODE_64I_REG.message" placement="top">
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <el-input :disabled="!isNew" v-model="formData.key" style="width: 520px" placeholder="请输入Key" :maxlength="64"
          show-word-limit />
      </el-form-item>

      <el-form-item v-for="(column, index) in formData.columns" :key="index" :label="index === 0 ? '字段' : ''"
        :prop="'columns.' + index + '.columnCode'" :rules="[
          {
            required: true,
            message: '字段不能为空',
            trigger: 'change',
          },
        ]">
        <div class="table-index__column">
          <el-select :disabled="!isNew" class="table-index__selector" v-model="formData.columns[index].columnCode">
            <el-option v-for="item in validModelFields" :key="item.code" :value="item.code" :disabled="item.disabled"
              :label="item.name + ' [' + item.code + ']'" />
          </el-select>

          <el-select :disabled="!isNew" class="table-index__selector" v-model="formData.columns[index].orderRule">
            <el-option class="table-index__option" v-for="item in TABLE_INDEX_ORDER_RULE" :key="item.value" :value="item.value" :label="item.value"
              :title="item.description" >
            </el-option>
          </el-select>
          <i v-if="isNew" class="el-icon-circle-plus table-index__icon" @click="handleColumnAdd(index)" />
          <i v-if="isNew" v-show="formData.columns.length > 1" class="el-icon-delete table-index__icon"
            @click="handleColumnRemove(index)" />
        </div>
      </el-form-item>
      <!-- </el-form-item> -->

      <el-form-item prop="uniqueFlag" label="唯一">
        <el-checkbox :disabled="!isNew" v-model="formData.uniqueFlag">是否唯一索引</el-checkbox>
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { TABLE_INDEX_ORDER_RULE } from "@/utils/enum";
import { COMMON_CODE_64I_REG } from "@/utils/reg";
import { postHmindex } from "@/apis/paas/HmIndexController.js";
import { getHmentitymodelList } from "@/apis/paas/HmEntityModelController.js";

const getDefaultData = () => {
  return {
    key: "",
    columns: [
      {
        columnCode: "",
        orderRule: TABLE_INDEX_ORDER_RULE[0].value,
      },
    ],
    uniqueFlag: false,
  };
};

export default {
  name: "TableIndexForm",
  components: {},

  data () {
    return {
      isNew: false,
      COMMON_CODE_64I_REG,
      TABLE_INDEX_ORDER_RULE,
      showVisible: false,
      formData: getDefaultData(),
      modelFields: [],
    };
  },

  props: {
    modelInfo: {
      type: Object,
      default: () => { },
    },
  },

  watch: {
    showVisible (value) {
      if (value) {
        console.log('showVisible value',value)
        this.loadModelFields()
      }
    }
  },

  computed: {
    validModelFields () {
      const usedFields = this.formData.columns.map(item => item.columnCode)
      console.log(usedFields)
      return this.modelFields.filter(item => item.code !== 'id').map(item => {
        if (usedFields.includes(item.code)) {
          item.disabled = true
        }
        return item
      })
    }
  },

  methods: {
    async addForm () {
      this.isNew = true
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    // async editForm (record = {}) {
    //   this.isNew = false
    //   this.showVisible = true;
    //   this.formData = {
    //     ...record,
    //   };
    //   this.$nextTick(() => {
    //     this.$refs.form.clearValidate();
    //   });
    // },

    async viewForm (record = {}) {
      this.isNew = false
      this.showVisible = true;
      this.formData = {
        ...record,
      };
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    handleCancel () {
      this.showVisible = false;
    },

    loadModelFields () {
      getHmentitymodelList({
        modelId: this.modelInfo.id,
        activated: true,
      }).then((res) => {
        this.modelFields = res;
      });
    },

    handleColumnAdd (index) {
      this.formData.columns.splice(index + 1, 0, {
        columnCode: "",
        orderRule: TABLE_INDEX_ORDER_RULE[0].value,
      });
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    handleColumnRemove (index) {
      this.formData.columns.splice(index, 1);
    },

    async submit () {
      try {
        await this.$refs.form.validate();
        postHmindex({
          ...this.formData,
          modelId: this.modelInfo.id
        }).then((res) => {
          this.$message.success("操作成功");
          this.handleCancel();
          this.$emit("ok");
        });
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.table-index__column {
  display: flex;
  align-items: center;
}

.table-index__selector {
  width: 250px;
  margin-right: 20px;
}
.table-index__option {
  width: 250px;
  overflow: hidden;
  height: auto;
}

.table-index__icon {
  font-size: 18px;
  color: #409eff;
  cursor: pointer;

  &.el-icon-delete {
    color: #ec2234;
    margin-left: 8px;
  }
}
</style>
